<?php
/**
 *
 * User: Jessica@aweb.wang
 * Date: 2023/3/10 14:50
 * Email: <1194323013@qq.com>
 *                            _ooOoo_
 *                           o8888888o
 *                           88" . "88
 *                           (| -_- |)
 *                           O\  =  /O
 *                        ____/`---'\____
 *                      .'  \\|     |//  `.
 *                     /  \\|||  :  |||//  \
 *                    /  _||||| -:- |||||-  \
 *                    |   | \\\  -  /// |   |
 *                    | \_|  ''\---/''  |   |
 *                    \  .-\__  `-`  ___/-. /
 *                  ___`. .'  /--.--\  `. . __
 *               ."" '<  `.___\_<|>_/___.'  >'"".
 *              | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *              \  \ `-.   \_ __\ /__ _/   .-` /  /
 *         ======`-.____`-.___\_____/___.-`____.-'======
 *                            `=---='
 *        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *                      Buddha Bless, No Bug !
 **/
namespace app\common\middleware;
use app\common\exception\BusinessException;
use app\common\exception\BusinessExceptionEnum;
use app\common\model\Applet;
use app\common\utils\TokenUtils;

class WApi extends Logger
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $respam=$request->param();
        if(isset($respam['sign_timestamp'])){
            if(time()-$respam['sign_timestamp']>180){
                throw new BusinessException(BusinessExceptionEnum::SIGN_WRONG);
            }
        }
        if($this->sign($respam)){
            $response = $next($request);
            return $response;

        }else{
            throw new BusinessException(BusinessExceptionEnum::SIGN_WRONG);
        }
    }
    private function sign($respam){
        $post=$respam;
        //排序
        $apwhere[]=['appid','=',$post['appid']];
        $iscunzai=Applet::where($apwhere)->find();
        if($iscunzai){
            unset($post['sign']);
            $sortpost=ksort($post);
            $signstr='';

            foreach ($post as$key=> $value) {
                $signstr=$signstr.'&'.$key.'='.$value;
            }
            $signstr=substr($signstr,1,strlen($signstr));
            $yssign=md5($signstr.$iscunzai['appsecret']);

            if($yssign!=$respam['sign']){
                return false;
            }else{
                return true;
            }
        }else{
            return false;
        }

    }

}